package org.example.managere.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        basePackages = "org.example.managere.repository.feibiao",
        entityManagerFactoryRef = "feibiaoEntityManager",
        transactionManagerRef = "feibiaoTransactionManager"
)
public class FeibiaoDataSourceConfig {
    @Bean(name = "feibiaoDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.feibiao")
    public DataSource feibiaoDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "feibiaoDatasourceJdbcTemplate")
    public JdbcTemplate jdbcTemplate(@Qualifier("feibiaoDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean(name = "feibiaoEntityManager")
    public LocalContainerEntityManagerFactoryBean feibiaoEntityManager() {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(feibiaoDataSource());
        em.setPackagesToScan("org.example.managere.entity.feibiao");

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);

        HashMap<String, Object> properties = new HashMap<>();
        properties.put("hibernate.hbm2ddl.auto", "update");
        properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
        
        // 添加LOB处理配置
        properties.put("hibernate.jdbc.batch_size", 100);
        properties.put("hibernate.jdbc.fetch_size", 100);
        properties.put("hibernate.jdbc.lob.non_contextual_creation", true);
        properties.put("hibernate.temp.use_jdbc_metadata_defaults", false);
        
        em.setJpaPropertyMap(properties);

        return em;
    }

    @Bean(name = "feibiaoTransactionManager")
    public PlatformTransactionManager feibiaoTransactionManager(
            @Qualifier("feibiaoEntityManager") LocalContainerEntityManagerFactoryBean feibiaoEntityManager) {
        return new JpaTransactionManager(feibiaoEntityManager.getObject());
    }
} 